import java.net.*;
import java.util.*;
import java.io.*;


public class FuxiBot {
	private static Socket server;
	private Scanner console;
	private String host;
	private int port;
	private BufferedReader socketI;
	private BufferedWriter socketO;
	private MessageParser middleman;
	private String password, nick, userLong;

	
	public FuxiBot()
	{
		middleman = new MessageParser();
		password = "derpalicious";
		nick = "Fuxibot";
		userLong = "Rusina 0 * :John Lindert";
		
		console = new Scanner(System.in);
		System.out.println("Please enter server to connect to.");
		host = console.nextLine();
		System.out.println("Please enter port.");
		port = console.nextInt();
		if (port == 0 | port > 65535)
			port = 6667;
		
		try
		{
			server = new Socket(host, port);
		} catch (Exception exc)
		{
			System.out.println(exc);
			System.out.println("Fatal error creating socket connection! Terminating..");
			System.exit(0);
		}
		
		try
		{
			socketI = new BufferedReader(new InputStreamReader(server.getInputStream()));
			socketO = new BufferedWriter(new OutputStreamWriter(server.getOutputStream()));
		} catch (Exception exc)
		{
			System.out.println(exc);
			System.out.println("Fatal error creating socket IO! Terminating..");
			System.exit(0);
		}
		
		try
		{
			socketO.write("PASS " + password);
			socketO.write("NICK " + nick);
			socketO.write("USER " + userLong);
		} catch (Exception exc)
		{
			System.out.println(exc);
			System.out.println("Fatal error creating registration! Terminating..");
			System.exit(0);
		}
		System.out.println("Entering socket loop..");
		socketLoop();
	}
	
	private void socketLoop()
	{
		while (true)
		{
			try
			{
				System.out.println("74");
				if (console.hasNextLine())
					socketO.write(console.nextLine());
				while (!socketI.ready()) {}
				System.out.println("78");
				while (socketI.ready())
				{
					System.out.println("81");
					System.out.println("87");
					if (middleman == null)
						System.out.println("dfklöjgndf");
					if (!socketI.ready())
						System.out.println("asdfasdfasdf");
					String[] returnArray = null;
					try
					{
						returnArray = middleman.read(socketI.readLine());
					} catch (Exception exc)
					{
						System.out.println("VOI VITTU");
						System.out.println(exc);
					}
					System.out.println("89");
					if(!(returnArray != null && returnArray.length != 0))
						break;
					System.out.println("92");
					for (int i=0; i<returnArray.length; i++)
						socketO.write(returnArray[i]);
					System.out.println("95");
				}
				
				
			} catch (Exception exc)
			{
				System.out.println(exc);
				System.out.println("Fatal error during socket wait! Terminating..");
				System.exit(0);
			}
		}
	}
	
	public static void main(String[] args)
	{
		new FuxiBot();
		System.out.println("main() terminated, exiting..");
	}

}
